import hashlib, io, random
from urllib import parse
from .utils import post
import api, ui
from .wrapper import jsonData
# 百度翻译接口URL
URL = "http://api.fanyi.baidu.com/api/trans/vip/translate"
# 百度翻译Appid
APPID = "20200703000512112"
# 百度翻译秘钥
SECURITYKEY = "jyV8SdX6LpZ0pmHbVbuQ"
def translateFromClipboard():
    # 从剪贴板翻译
    translate(api.getClipData(), 'auto', 'auto')
def translate(query, fromLang, toLang):
    # 翻译接口
    salt = str(random.randrange(10000, 99999)) # 随机数
    sig = APPID + query + salt + SECURITYKEY # 签名内容
    params = {
      'q': query,
      'from': fromLang,
      'to': toLang,
      'appid': APPID,
      'salt': salt,
      'sign': hashlib.new('md5', sig.encode()).hexdigest()
    }
    @jsonData
    def get():
        return post(URL, parse.urlencode(params).encode(), {'Content-Type': 'application/x-www-form-urlencoded'})
    try:
        res = get()
        if 'error_code' in res.keys() and int(res['error_code']) != 0:
            raise Exception(res['error_msg'])
        res = res['trans_result']
        if not res:
            raise Exception('No result.')
        content = io.StringIO()
        for line in res:
            content.write('<h1>原文：</h1>')
            content.write('<p>' + line['src'] + '</p>')
            content.write('<h1>译文：</h1>')
            content.write('<p>' + line['dst'] + '</p>')
        text = content.getvalue()
        content.close()
        ui.browseableMessage(text, '翻译结果', True)
    except Exception as e:
        ui.message(str(e))